package com.wedata.weapp;

import com.alibaba.fastjson2.JSONObject;
import cn.hutool.crypto.digest.MD5;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.UUID;

/**
 * BTW接口服务
 */
public class BetterWeApiService {

    private static final String appid = "17259611052";//公钥 : 接口提供方，通过公钥去找到对应的私钥验签
    private static final String secret = "3aea2efeeb54184f76db4831c3fc1b9f";//私钥请妥善保管，不要泄露

    public static void main(String[] args) {
        new BetterWeApiService().register();
    }
    /**
     * 调注册方法
     * @return
     */
    public JSONObject register() {
        JSONObject body = new JSONObject();//post请求的body对象
        body.put("source_from",1);//素材来源 【1：燃脂计划 2：营养课程 3：塑形】
        body.put("code", "123123");//芒果tv-优惠码
        body.put("uuid", "123321");//芒果tv-uuid

        String resultStr = requestBtw("https://tbtapp.gymcity.com.cn/externalinterfaces/Register/mgToBtw", body);
        JSONObject result = JSONObject.parseObject(resultStr);
        System.out.println(result);
        //响应示例
        //{"code":200,"msg":"ok","time":"1726045758","data":{"id":2,"mgtv_uuid":"123321","mgtv_code":"123123","incoming_code":"https://work.weixin.qq.com/ca/cawcde3c6dfa1a2bac?customer_channel=qywx_ca:106616881","unfiy_id":0,"source_from":1,"created_at":"2024-09-11 17:03:18","updated_at":"2024-09-11 17:03:18"}}
        return result;
    }

    /**
     * 签名算法示例
     * @return
     */
    public String requestBtw(String apiUrl, JSONObject body){
        //签名算法直接拼接md5即可
        String sign = MD5.create().digestHex(body +"#"+secret);
        JSONObject header = new JSONObject();//请求头部
        header.put("sign",sign);//把签名信息放到头部
        header.put("request_id", UUID.randomUUID());//这里是请求UUID，用于链路追踪
        header.put("appid", appid);//
        String resultStr = sendPostRequest(apiUrl, header, body);
        return resultStr;
    }

    /**
     * POST请求封装
     * @param uri
     * @param header
     * @param body
     * @return
     */
    public static String sendPostRequest(String uri, JSONObject header, JSONObject body){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            connection.setConnectTimeout(3000);// 3秒 连接超时时间（单位毫秒）
            connection.setReadTimeout(5000);// 5秒 读取数据超时时间（单位毫秒）

            //设置header
            if(header != null){
                final Set<String> keySet = header.keySet();
                for(String key:keySet) {
                    connection.setRequestProperty(key,header.getString(key));
                }
            }
            connection.connect();
            System.out.println("sendPost uri=" + uri +",param="+ body.toJSONString() + ",header=" + header);
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body.toJSONString().getBytes());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while((lines=reader.readLine())!=null){
                lines = new String(lines.getBytes(StandardCharsets.UTF_8));
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            System.out.println("sendRequest result:" + sb);
            return sb.toString();
        }catch (SocketTimeoutException e){
            System.out.println("连接超时异常");
        }catch (Exception e){
            System.out.println("sendRequest uri=" + uri +",param="+ body.toJSONString() + ",header=" + header+",happen exception.");
            e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }
}
